package com.sunxd.zstudy.juc.T19_container.fromHashTableToConcurrentHashMap.readEffficiency;

import com.sunxd.zstudy.juc.T19_container.fromHashTableToConcurrentHashMap.addEfficiency.EfficiencyConstants;

import java.util.HashMap;
import java.util.stream.Stream;

/**
 * @author: 作者名称
 * @date: 2021-09-09 15:51
 **/
public class ReadHashMap {

    static HashMap<Integer, Integer> map = new HashMap<>();

    static class MyThread extends Thread {

        int start;
        int gap = EfficiencyConstants.COUNT / EfficiencyConstants.THREAD_COUNT;

        public MyThread(int start) {
            this.start = start;
        }

        @Override
        public void run() {
            for (int i = start; i < start + gap; i++) {
                map.put(i, i);
            }
        }

    }

    public static void main(String[] args) throws InterruptedException {
        Thread[] threads = new Thread[EfficiencyConstants.THREAD_COUNT];
        for (int i = 0; i < threads.length; i++) {
            threads[i] = new MyThread(i * EfficiencyConstants.COUNT / EfficiencyConstants.THREAD_COUNT);
        }
        for (Thread t : threads) {
            t.start();
        }
        for (Thread t : threads) {
            t.join();
        }
        System.out.println(map.size());
        long start = System.currentTimeMillis();
        for (int i = 0; i < EfficiencyConstants.THREAD_COUNT; i++) {
            threads[i] = new Thread(() ->{
                for (int j = 0; j < EfficiencyConstants.COUNT; j++) {
                    map.get(j);
                }
            });
        }
        Stream.of(threads).forEach(Thread::start);
        for (Thread thread : threads) {
            thread.join();
        }
        System.out.println(System.currentTimeMillis() - start);

    }


}
